import { useIntersectionObserver, useIntervalFn } from "@vueuse/core"
import { onMounted, onUnmounted, ref } from "vue"

export function useLazyData(apiFn: () => void) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    if (isIntersecting) {
      stop()
      apiFn()
    }
  }, { threshold: 0 })
  return target
}

export function useHMScrollY() {
  const y = ref(0)
  // 监听滚动条的滚动，获取滚动的距离，滚动距离>=78的时候，动态设置show类
  // 等dom加载完，注册监听事件 created(vue3中直接写setup中) mounted(注册生命周期事件)
  const onScroll = () => {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    y.value = scrollTop
    console.log('scrollTop:', scrollTop);
  }
  onMounted(() => {
    window.addEventListener('scroll', onScroll)
  })
  // beforeDestroy 准备要卸载组件了，事件清一清
  // onBeforeUnmount
  onUnmounted(() => {
    window.removeEventListener('scroll', onScroll)
  })
  return y
}

export function useCountDown(count: number = 60) {
  const time = ref(0);
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--;
      if (time.value <= 0) {
        pause();
      }
    },
    1000,
    { immediate: false }
  );
  const start = () => {
    // 初始化倒计时秒数
    time.value = count;
    // 开始倒计时
    resume();
  }
  // 如果组件被卸载了，也要清除定时器
  onUnmounted(() => {
    pause();
  })
  return {
    time,
    start
  }
}